package cn.com.demo.filter;

import cn.com.demo.common.vo.BaseRepVo;
import cn.com.demo.config.MyUser;
import cn.com.demo.config.MyTokenConfig;
import cn.com.demo.entity.UserInfo;
import cn.com.demo.util.LocalCache;
import cn.com.demo.util.ResponseUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;

public class MyTokenLoginFilter extends UsernamePasswordAuthenticationFilter {
    private AuthenticationManager authenticationManager;
    MyTokenConfig myTokenConfig;

    public MyTokenLoginFilter(AuthenticationManager authenticationManager, MyTokenConfig myTokenConfig) {
        this.authenticationManager = authenticationManager;
        this.myTokenConfig = myTokenConfig;
        // 设置登录地址及请求方式 (默认:/login POST)
        this.setRequiresAuthenticationRequestMatcher(new AntPathRequestMatcher("/noauth/sublogin", "POST"));
    }

    // 获取登录信息
    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
        try {
            // 修改获取用户名密码的过程 ,对于前后端分离项目中密码加密存储时，在这一步进行密码解密 以保证密码能正确处理密码信息
            UserInfo userInfo = new ObjectMapper().readValue(request.getInputStream(), UserInfo.class);
            // 提交security处理认证过程
            return authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(userInfo.getUsername(), userInfo.getPassword(), new ArrayList<GrantedAuthority>()));
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException("获取认证信息异常");
        }
    }

    @Override
    protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response, FilterChain chain, Authentication authResult) throws IOException, ServletException {
        System.out.println("登录成功");
        // 获取认证成功信息
        MyUser user = (MyUser) authResult.getPrincipal();
        // 缓存权限信息
        LocalCache.put(user.getUsername(),user.getAuthorities());
        // 生成token
        String token = myTokenConfig.getToken(user.getUsername());
        HashMap<String,String> data = new HashMap<>();
        data.put("token",token);
        ResponseUtil.out(response,new BaseRepVo(data));
    }

    @Override
    protected void unsuccessfulAuthentication(HttpServletRequest request, HttpServletResponse response, AuthenticationException failed) throws IOException, ServletException {
        System.out.println("登录失败");
        ResponseUtil.error(response,failed.getMessage());
    }
}
